/**
 * 弹框上传代码
 * Created by suweiming on 2018/1/19.
 */
(function ($) {
    var img_jcrop = '';

    function onchange(eleId, wh) {
        ajaxFileUpload({
            eleId: eleId,
            url: wh.url || '',
            data: wh.extraData || {}
        }, function (data) {
            if (!data) {
                $("#" + eleId).unbind('change').on('change', function () {
                    onchange(eleId, wh);
                });
                return;
            }
            if (wh.plain) {
                $("#" + eleId).unbind('change').on('change', function () {
                    onchange(eleId, wh);
                });
                return wh.submit(data.data,data);
            }
            $("#target").attr("src", data.data.path);
            $("#target").css('width', '100%');
            $("#target").data('fileId', data.data.fileId);
            $('.preview-container img').attr('src', data.data.path);
            if (wh.previewClass) {
                $('.' + wh.previewClass).attr('src', data.data.path);
            }

            if (wh.submitEachTime) {
                wh.submitEachTime(data.data.path,data);
            }

            form = null;
            if (!wh.noCrop) {

                path = data.data.path;
                if (img_jcrop && img_jcrop.destroy && img_jcrop.destroy instanceof 'function') {
                    img_jcrop.destroy();
                }
                $("#target").load(function () {
                    $('.jc-demo-box').show();
                    initJCrop(wh);
                });
            } else {
                $('.preview-upload-image').html('<a target="_blank" href="' + data.data.path + '" title="新页面打开预览"><img src="' + data.data.path + '" style="width:100%;"></a>');
                wh.submit(data.data);
            }
            $("#" + eleId).unbind('change').on('change', function () {
                onchange(eleId, wh);
            });
        });
    }

    var $Uploader = {
        init: function (options) {
            var $sel = $(this);
            $sel.parent().css({position: 'relative'});
            var $file = $('<input type="file" name="file" />');
            var $container = $('<div>');
            var $a = $('<a>');
            $a.html(options.label || ' 选 择 ');
            $a.addClass('btn btn-primary').css({
                margin: '10px 10px 0 0'
            });
            $container.append($file); //
            $container.append($a); //
            $container.css({'position': 'relative'}).addClass($sel.attr('class'));
            var $id = 'upload-' + parseInt(Math.random() * 10000);
            $file.attr('id', $id);
            $file.hide();
            $sel.replaceWith($container);
            onClick($a, function () {
                $("#" + $id).click();
            });
            $('#save').appendTo($a.parent());
            $("#" + $id).unbind('change').on('change', function () {
                onchange($id, options)
            });
        },
        initBtn: function () {
        }
    };
    $.fn.$upload = function (options) {
        var _default = {
            fields: []
        };
        options = $.extend({}, _default, options || {});
        $(this).html('<div>加载中...</div>');
        return this.each(function () {
            $Uploader.init.call(this, options);
        });
    };
    var boundx,
        boundy;
    // 裁剪功能
    $.$jCrop = initJCrop;

    function initJCrop(ratio) {
        if (ratio.path) {
            $("#target").attr("src", ratio.path);
            $("#target").css('width', '100%');
            $("#target").data('fileId', ratio.fileId);
            $('.preview-container img').attr('src', ratio.path);
            if (ratio.previewClass) {
                $('.' + wh.previewClass).attr('src', ratio.path);
            }
            path = ratio.path;
        }

        var jcrop_api,
            $preview = $('#preview-pane'),
            $pcnt = $('#preview-pane .preview-container'),
            $pimg = $('#preview-pane .preview-container img');

        $pcnt.show();
        $pcnt.css({
            width: ratio.w || 107,
            height: ratio.h || 142
        });
        var xsize = $pcnt.width(),
            ysize = $pcnt.height();
        img_jcrop = $('#target').Jcrop({
            onChange: updatePreview, // 拖动事件
            onSelect: updatePreview, // 选择事件
            setSelect: [0, 0, ratio.w || 107, ratio.h || 142], // 设置默认选择区
            aspectRatio: (ratio.w || 107) / (ratio.h || 142) // 设置选择宽高比例
        }, function () {
            // Use the API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            jcrop_api = this;
            // $preview.appendTo(jcrop_api.ui.holder);
            transformNaturalSize({x: 0, y: 0, w: ratio.w || 107, h: ratio.h || 142}, boundx, boundy);
        });
        onClick($('#save'), function () {
            form.path = path;
            if (!!$("#target").data('fileId')) {
                form.fileId = $("#target").data('fileId');
            }
            ;
            // $.post('/path-cut-image-oss', form, function (data) {
            $.post('/path-cut-image', form, function (data) {
                $('.jc-demo-box').hide();
                fnSuccess && fnSuccess('保存成功!');
                ratio.submit && ratio.submit(data.data);
                //   $('#container_photo').html('<img style="width:100%;" src="' + data.data.path + '" />')
            });
        });
        function updatePreview(c) {
            if (boundx) {
                transformNaturalSize(c, boundx, boundy);
            }
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                if (!boundy) {
                    boundy = $('#target').height();
                }
                $pimg.css({
                    width: 'auto',
                    // width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });

            }
        };
        function transformNaturalSize(c, boundx, boundy) {
            var obj = getNatural();
            form = {};
            var xradio = obj.w / boundx;
            var yradio = obj.h / boundy;
            var radio = yradio > xradio ? yradio : xradio;

            form.w = Math.round(xradio * c.w);
            form.h = Math.round(yradio * c.h);
            form.y = Math.round(yradio * c.y);
            form.x = Math.round(xradio * c.x);
        }

        function getNatural() {
            var myimage = $('img[src="' + path + '"]')[0];
            if (typeof myimage.naturalWidth == "undefined") {
                // IE 6/7/8
                var i = new Image();
                i.src = path;
                return {
                    w: i.width,
                    h: i.height
                };
            }
            else {
                // HTML5 browsers
                var rw = myimage.naturalWidth;
                var rh = myimage.naturalHeight;
                return {
                    w: rw,
                    h: rh
                };
            }

        }
    }
})(jQuery);